<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  <title>Promise</title>
  <style type="text/css">
  * {
        padding: 0;
        margin: 0;
    }
    </style>
</head>
<body>
   <div class="box">
     <h2>Promise</h2>
   </div>
  <script src="index.js"></script>
  <script src="php/ajax.js"></script>
  <script type="text/javascript">
class User {
  //加载用户
  ajax(user) {
    let url = `http://localhost:8888/php/user.php?name=${user}`;
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.send();
      xhr.onload = function() {
        if (this.status == 200) {
          resolve(JSON.parse(this.response));
        } else {
          reject(this);
        }
      };
    }).catch(reason => {
      console.warn(reason)
    });
  }
  //启动
  render(users) {
    users.reduce((promise, user) => {
      return promise
        .then(() => {
          return this.ajax(user);
        })
        .then(user => {
          if(user)
            return this.view(user);
        });
    }, Promise.resolve());
  }
  //宣染视图
  view(user) {
    return new Promise(resolve => {
      let h1 = document.createElement("h1");
      h1.innerHTML = user.name;
      document.body.appendChild(h1);
      resolve();
    });
  }
}
new User().render(["向军",  "刘阿勇", "后盾人"]);

  </script>
</body>
</html>